package com.lyc.mall.controller.admin;

import com.google.gson.Gson;
import com.lyc.mall.model.BO.AdminAddBO;
import com.lyc.mall.model.BO.AdminLoginBO;
import com.lyc.mall.model.BO.AdminSearchBO;
import com.lyc.mall.model.VO.AdminInfoVO;
import com.lyc.mall.model.VO.AdminLoginVO;
import com.lyc.mall.service.AdminService;
import com.lyc.mall.service.impl.AdminServiceImpl;
import com.lyc.mall.util.HttpUtils;
import com.lyc.mall.util.Result;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {
    AdminService adminService = new AdminServiceImpl();
    Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String operation = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        if ("allAdmins".equals(operation)) {
            allAdmins(request, response);
        } else if ("getAdminsInfo".equals(operation)) {
            getAdminsInfo(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求头中访问的资源对应的方法名
        String requestURI = request.getRequestURI();
        // login
        String operation = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        if ("login".equals(operation)) {
            login(request, response);
        } else if ("addAdminss".equals(operation)) {
            addAdminss(request, response);
        } else if ("getSearchAdmins".equals(operation)) {
            getSearchAdmins(request, response);
        } else if ("logoutAdmin".equals(operation)) {
            logoutAdmin(request, response);
        }
    }

    /**
     * 登录admin账号
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求体参数
        String requestBody = HttpUtils.getRequestBody(request);
        // 接下来要将这个JSON字符串转换为Java对象进行处理
        // 项目中对象分为BO VO PO
        AdminLoginBO loginBO = gson.fromJson(requestBody, AdminLoginBO.class);
        // 校验
        // 判空
        if (StringUtils.isEmpty(loginBO.getEmail()) || StringUtils.isEmpty(loginBO.getPwd())) {
            // 失败响应
            // 如果希望对接成功，则需要在响应体中写入json字符串
            response.getWriter().println(gson.toJson(Result.ERROR("!用户名、密码不能为空")));
            return;
        }
        // 调用service层方法查询用户是否存在,成功返回200，不成功返回404
        int code = adminService.loginBO(loginBO);
        // 登陆成功之后往session域存数据
        HttpSession session = request.getSession();
        session.setAttribute("email", loginBO.getEmail());
        if (code == 200) {
            // 登陆成功
            response.getWriter().println(gson.toJson(Result.OK(new AdminLoginVO(loginBO.getEmail(), loginBO.getEmail()))));
        } else if (code == 404) {
            // 登陆失败
            response.getWriter().println(gson.toJson(Result.ERROR("!用户名或密码错误")));
        }
    }

    /**
     * 查询当前系统中所有的管理员账号,不需要携带请求参数
     * // 任何一个接口都可以分为三步走
     * 1、获取请求参数
     * 2、处理当前业务的具体逻辑
     * 3、根据开发接口返回相应的json字符串
     *
     * @param request
     * @param response
     */
    private void allAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<AdminInfoVO> adminInfoVOs = adminService.allAdmins();
        // 响应体返回数据
        response.getWriter().println(gson.toJson(Result.OK(adminInfoVOs)));
    }

    /**
     * 新增管理员的业务逻辑
     * 1、获取请求参数
     * 2、处理当前业务的具体逻辑
     * 3、根据开发接口返回相应的json字符串
     * 返回值：{"code：0}
     *
     * @param request
     * @param response
     */
    private void addAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminAddBO adminAddBO = gson.fromJson(requestBody, AdminAddBO.class);
        // 判空
        if (StringUtils.isEmpty(adminAddBO.getEmail()) || StringUtils.isEmpty(adminAddBO.getNickname()) || StringUtils.isEmpty(adminAddBO.getPwd())) {
            // 返回错误的信息
            response.getWriter().println(gson.toJson(Result.ERROR("信息不能为空")));
            return;
        }
        // 方法的执行结构有多种可能性需要返回值，否则不需要
        int code = adminService.addAdmin(adminAddBO);
        if (code == 200) {
            // 新增成功
            response.getWriter().println(gson.toJson(Result.OK()));
        } else {
            // 新增失败
            response.getWriter().println(gson.toJson(Result.ERROR("用户名重复")));
        }
    }

    /**
     * 业务逻辑：
     * 获取到当前感力源的详细信息
     * 使用的是get请求方法，地址栏后面附着了id=xxx的参数
     * 对应的sql语句应该是：select * from admin where id = ?
     * 1、获取请求参数：id = xxx request.getParameter
     * 2、数据库中进行查询操作
     * 3、返回结果 admin信息
     *
     * @param request
     * @param response
     */
    private void getAdminsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)) {
            response.getWriter().println(gson.toJson(Result.ERROR("参数不能为空")));
            return;
        }
        int adminID = 0;
        try {
            adminID = Integer.parseInt(id);
        } catch (NumberFormatException e) {
            response.getWriter().println(gson.toJson(Result.ERROR("编号必须是数字")));
            return;
        }
        AdminInfoVO adminInfoVO = adminService.getAdminInfo(adminID);
        response.getWriter().println(gson.toJson(Result.OK(adminInfoVO)));
    }

    /**
     * 业务逻辑：
     * 用户在页面输入管理员账号、昵称，进行组合条件的搜索
     * 如果两个参数均输入
     * select * from admin where username like ? and nickname like ?
     * 如果只输入用户名
     * select * from admin where username like ?
     * 如果只输入昵称
     * select * from admin where nickname like ?
     * 如果两者都不输入
     * select * from admin;
     * 1、获取请求参数
     * request.getParameter(username)
     * request.getParameter(nickname)
     * 2、执行具体的业务逻辑：动态sql
     * 3、返回结果
     *
     * @param request
     * @param response
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminSearchBO adminSearchBO = gson.fromJson(requestBody, AdminSearchBO.class);
        // 此时不需要判空，即便为空也需要执行sql语句
        List<AdminInfoVO> adminInfoVOList = adminService.getSearchAdmins(adminSearchBO);
        response.getWriter().println(gson.toJson(Result.OK(adminInfoVOList)));
    }

    /**
     * 退出登录
     * @param request
     * @param response
     */
    private void logoutAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        // 销毁当前session
        session.invalidate();
        response.getWriter().println(gson.toJson(Result.OK()));
    }
}
